'use strict'
const path = require('path')
const defaultSettings = require('./my-config.js')

function resolve(dir) {
  return path.join(__dirname, dir)
}

const assetsCDN = {
  // webpack build externals
  externals: {
    vue: 'Vue',
    'vue-router': 'VueRouter',
    vuex: 'Vuex',
    axios: 'axios',
    echarts: 'echarts'
  },
  css: [],
  // https://unpkg.com/browse/vue@2.6.10/
  js: [
    '//unpkg.zhimg.com/vue@2.6.10/dist/vue.min.js',
    '//unpkg.zhimg.com/vue-router@3.0.6/dist/vue-router.min.js',
    '//unpkg.zhimg.com/vuex@3.1.0/dist/vuex.min.js',
    '//unpkg.zhimg.com/axios@0.18.1/dist/axios.min.js',
    '//unpkg.zhimg.com/echarts@4.9.0/dist/echarts.min.js'
  ]
}

// page title
const name = defaultSettings.title || 'cms管理系统'

// dev port
const port = process.env.port || process.env.npm_config_port || 9528

// isProd
const isProd = process.env.NODE_ENV === 'production'

module.exports = {

  publicPath: '/',
  outputDir: 'dist',
  assetsDir: 'static',
  // eslint-loader 是否在保存的时候检查
  lintOnSave: !isProd,
  // 生产环境是否生成 sourceMap 文件
  productionSourceMap: false,
  devServer: {
    port,
    hot: true,
    overlay: {
      warnings: false,
      errors: true
    },
    proxy: {
      // https://blog.csdn.net/a772116804/article/details/115244913
      [process.env.VUE_APP_BASE_API]: {
        target: defaultSettings.serviceApi[process.env.NODE_ENV], // 这个链接是要代理到的api地址
        changeOrigin: true,
        secure: false, // 如果是https接口，需要配置这个参数
        pathRewrite: {
          ['^' + process.env.VUE_APP_BASE_API]: ''
        },
        onProxyRes(proxyRes, req, res) {
          // 获取登录接口中的相应头中的set-cookie，整理之后放到请求头中
          var oldCookie = proxyRes.headers['set-cookie']
          if (oldCookie == null || oldCookie.length === 0) {
            delete proxyRes.headers['set-cookie']
            return
          }
          var oldCookieItems = oldCookie[0].split(';')
          var newCookie = ''
          for (var i = 0; i < oldCookieItems.length; ++i) {
            if (newCookie.length > 0)
              newCookie += ';'
            if (oldCookieItems[i].toLowerCase().indexOf('path=') >= 0)
              newCookie += 'path=/'
            else
              newCookie += oldCookieItems[i]
          }
          proxyRes.headers['set-cookie'] = [newCookie]
        }
      }
    }
  },
  configureWebpack: {
    // 在webpack的name字段中提供应用程序的标题，以便可以在index.html中访问它以注入正确的标题。
    name,
    resolve: {
      // 路径别名，要保持ide的快捷跳转不会失效，请在修改或添加后也对应修改 jsconfig.json 中的路径别名
      alias: {
        '@': resolve('src'),
        '@c': resolve('src/components'),
        '@l': resolve('src/layout'),
        '@v': resolve('src/views'),
        '@u': resolve('src/utils'),
        '@img': resolve('src/assets'),
        '@api': resolve('src/api')
      }
    },
    // if prod, add externals
    externals: isProd ? assetsCDN.externals : {}
  },
  chainWebpack(config) {
    // config.plugins.delete('preload')
    // 它可以提高第一个屏幕的速度，建议打开预加载
    config.plugin('preload').tap(() => [
      {
        rel: 'preload',
        // https://github.com/vuejs/vue-cli/blob/dev/packages/@vue/cli-service/lib/config/app.js#L171
        fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],
        include: 'initial'
      }
    ])

    config.plugins.delete('prefetch') // 空闲加载

    // set svg-sprite-loader
    config.module
      .rule('svg')
      .exclude.add(resolve('src/icons'))
      .end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()

    // set preserveWhitespace
    config.module
      .rule('vue')
      .use('vue-loader')
      .loader('vue-loader')
      .tap(options => {
        options.compilerOptions.preserveWhitespace = true
        return options
      })
      .end()

    config
      // https://webpack.js.org/configuration/devtool/#development
      .when(process.env.NODE_ENV === 'development',
        config => config.devtool('cheap-source-map')
      )

    config
      .when(process.env.NODE_ENV !== 'development',
        config => {
          config
            .plugin('ScriptExtHtmlWebpackPlugin')
            .after('html')
            .use('script-ext-html-webpack-plugin', [{
              // `runtime` must same as runtimeChunk name. default is `runtime`
              inline: /runtime\..*\.js$/
            }])
            .end()
          config
            .optimization.splitChunks({
              chunks: 'all',
              cacheGroups: {
                libs: {
                  name: 'chunk-libs',
                  test: /[\\/]node_modules[\\/]/,
                  priority: 10,
                  chunks: 'initial' // 只打包初始时依赖的第三方
                },
                elementUI: {
                  name: 'chunk-elementUI', // 单独将 elementUI 拆包
                  priority: 20, // 权重要大于 libs 和 app 不然会被打包进 libs 或者 app
                  test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
                },
                commons: {
                  name: 'chunk-commons',
                  test: resolve('src/components'), // can customize your rules
                  minChunks: 3, //  minimum common number
                  priority: 5,
                  reuseExistingChunk: true
                }
              }
            })
          config.optimization.runtimeChunk('single')
        }
      )

    // if prod is on
    // assets require on cdn
    if (isProd) {
      config.plugin('html').tap(args => {
        args[0].cdn = assetsCDN
        return args
      })
    }
  },

  css: {
    loaderOptions: {
      // 给 sass-loader 传递选项
      // 默认情况下 `sass` 选项会同时对 `sass` 和 `scss` 语法同时生效
      // 因为 `scss` 语法在内部也是由 sass-loader 处理的
      // 但是在配置 `prependData` 选项的时候
      // `scss` 语法会要求语句结尾必须有分号，`sass` 则要求必须没有分号
      // 在这种情况下，我们可以使用 `scss` 选项，对 `scss` 语法进行单独配置
      // sass: {
      //   // 注意：在 sass-loader v8 中，这个选项名是 "prependData"
      //   additionalData: `@import "@/styles/mixin.scss";`
      // }
    }
  }
}
